/**
 * <p>Title: ServiceZMCMB2.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-26 上午09:56:02  张小飞  Create
 *</pre>
 */
package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cm.Depot;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBasicInfo;

/**
 * <p>Title: ServiceZMCMB2.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张小飞
 * @version 1.0
 * <pre>Histroy:
 *          2011-7-26 上午09:56:02  张小飞  Create
 *</pre>
 */
public class ServiceZMCMB2 extends ServiceEPBase {

	/**
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMB2</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-26上午10:04:13 张小飞
	 * </p>
	 *
	*/
	@SuppressWarnings("unchecked")
	@Override
	public EiInfo insert(EiInfo inInfo) {
		//校验没有重复的单据
		boolean isRepeat = validate(inInfo, "ZMCMImportMaterial.validate", new HashMap<String, String>());
		if(isRepeat) {
			return inInfo;
		}
		else {
			List<String> _list = new ArrayList<String>();
			Map<String,List<String>> params = new HashMap<String,List<String>>();
			
			String importType = inInfo.getBlock("baseBlock").getCellStr(0, "fdImportType");//入库类型
			int importFlag = 0;//超前入库
			
			if(importType.equals("一般入库"))
			{
				importFlag = 1;
			}
			else if(importType.equals("估收入库"))
			{
				importFlag = 2;
			}
			
			//入库记录
			String imKey = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL");
			inInfo.getBlock("baseBlock").setCell(0, "fdKeyId", imKey);//主键
			inInfo.getBlock("baseBlock").setCell(0, "fdDepotCode", Depot.getDepots().get(0).getFdDepotCode());
			inInfo.getBlock("baseBlock").setCell(0, "fdDepotName", Depot.getDepots().get(0).getFdDepotName());
			inInfo.getBlock("baseBlock").setCell(0, "fdEditor", UserSession.getUserId());
			inInfo.getBlock("baseBlock").setCell(0, "fdYear", MaterialBase.getAccountDate(inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteDate"))[0]);
			inInfo.getBlock("baseBlock").setCell(0, "fdMonth", MaterialBase.getAccountDate(inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteDate"))[1]);
			super.insert(inInfo, "ZMCMImportMaterial.insert", "baseBlock");
			
			//入库记录明细
			for(int i = 0; i < inInfo.getBlock("result").getRowCount(); i++){
				inInfo.getBlock("result").setCell(i, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL_DETAIL"));//主键
				inInfo.getBlock("result").setCell(i, "fdImportmaterialId", imKey);
				inInfo.getBlock("result").setCell(i, "fdConfirmPeople", inInfo.getBlock("baseBlock").getCellStr(0, "fdConfirmPeople"));
			}
			EiInfo outInfo = super.insert(inInfo, "ZMCMImportmaterialDetail.insert");
			
			for(int i = 0; i < inInfo.getBlock("result").getRowCount(); i++){
				_list.add(inInfo.getBlock("result").getCellStr(i, "fdMaterialId"));
			}
			params.put("fdMaterialIds", _list);
			List<ZMCMMaterialBase> updateList = dao.query("ZMCMMaterialBase.hasMaterialBase", params);//查出库存已有的物资
			
			if(updateList != null && !updateList.isEmpty()){//更新（部分或者全部）库存
				if(updateList.size() < inInfo.getBlock("result").getRowCount()){
					this.part(inInfo, updateList, importFlag);//部分更新
				}else if(updateList.size() == inInfo.getBlock("result").getRowCount()){
					this.updateAll(inInfo, updateList, importFlag);//全部更新
				}
			}else if(updateList != null && updateList.isEmpty()){//全部新增库存
				this.insertAll(inInfo, importFlag);
			}	
			
			return outInfo;
		}
	}
	
	/**
	 * 结转年月重复验证
	 * <p>Function: validateNo</p>
	 * <p>Description: </p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-1-13下午08:13:00 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(EiInfo inInfo, String sqlName, Map<String, String> params) {
		if(params == null) {
			params = new HashMap<String, String>();
		}
		
		String fdNoteCode = inInfo.getBlock("baseBlock").getCellStr(0, "fdNoteCode");
		params.put("fdNoteCode", fdNoteCode);
		
		List result = dao.query(sqlName, params);
		if(result != null && result.size() > 0) {
			inInfo.setStatus(-1);
			StringBuffer msg = new StringBuffer("提交失败，");
			msg.append(" 单据编号 ");
			msg.append("重复！");
			inInfo.setMsg(msg.toString());
			return true;
		}
		return false;

	}
	
	/**
	 * 
	 * <p>Function: queryforCustomview</p>
	 * <p>Description: 物资信息的界面视图customview</p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-18上午10:54:04 张小飞
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo queryforCustomview(EiInfo inInfo) 
	{
		Map inMap = new HashMap();
		String typeCode = "";
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdImportPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			List queryList = Utils.generateValidateData(_list);
			
			typeCode = "(FD_MATERIAL_CODE like ''";
			for(int i=0; i<queryList.size(); i++)
			{
				typeCode += " OR FD_MATERIAL_CODE like '" + queryList.get(i).toString() + "%'";
			}
			typeCode += ")";
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			List queryList = dao.query(sqlmap, inMap);
			
			typeCode = "(FD_MATERIAL_CODE like ''";
			for(int i=0; i<queryList.size(); i++)
			{
				Map _map = (Map)queryList.get(i);
				typeCode += " OR FD_MATERIAL_CODE like '" + _map.get("fdTypeCode").toString() + "%'";
			}
			typeCode += ")";
		}
		
		StaticTools.setQueryParameters(inInfo, "fdMaterialCodeStr", typeCode, true);
		StaticTools.setQueryParameters(inInfo, "fdMaterialStatus", "在用", true);
		EiInfo outInfo = super.query(inInfo, "ZMCMMaterialBasicInfo.query", new ZMCMMaterialBasicInfo());
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: insertAll</p>
	 * <p>Description: </p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:30:19 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void insertAll(EiInfo inInfo, int isNormalImport)
	{
		String fdYear = StaticTools.getYear();
		String fdMonth = StaticTools.getStringMonth();
		List month_list = dao.query("ZMCMMaterialBase.queryYearMonth", new HashMap());
		
		if(month_list.size() > 0)
		{
			fdYear = ((Map)month_list.get(0)).get("fdYear").toString();
			fdMonth = ((Map)month_list.get(0)).get("fdMonth").toString();
		}
		
		for(int i = 0; i < inInfo.getBlock("result").getRowCount(); i++){
			
			Map inMap = new HashMap();
			inMap.put("fdKeyId", inInfo.getBlock("result").getCellStr(i, "fdMaterialId"));
			List _list = dao.query("ZMCMMaterialBasicInfo.query", inMap);
			ZMCMMaterialBasicInfo basicInfo = (ZMCMMaterialBasicInfo)_list.get(0);
			
			String actualNumber = inInfo.getBlock("result").getCellStr(i, "fdActualNumber");
			
			String sum = inInfo.getBlock("result").getCellStr(i, "fdSum");
			double fdActualNumber = Double.parseDouble(actualNumber.equals("")? "0": actualNumber);
			double fdSum = Double.parseDouble(sum.equals("")? "0": sum);
			
			String invoiceSum = inInfo.getBlock("result").getCellStr(i, "fdInvoiceSum");
			double fdInvoiceSum = Double.parseDouble(invoiceSum.equals("")? "0": invoiceSum);
			
			
			inInfo.getBlock("result").setCell(i, "fdKeyId", TablePk.getInstance().getNextValue("T_CM_MATERIALBASE"));
			inInfo.getBlock("result").setCell(i, "fdDepotCode", Depot.getDepots().get(0).getFdDepotCode());
			inInfo.getBlock("result").setCell(i, "fdDepotName", Depot.getDepots().get(0).getFdDepotName());
			inInfo.getBlock("result").setCell(i, "fdYear", fdYear);
			inInfo.getBlock("result").setCell(i, "fdMonth", fdMonth);
			inInfo.getBlock("result").setCell(i, "fdBusinessType", "正常入库");
			inInfo.getBlock("result").setCell(i, "fdNum", fdActualNumber);//数量为实进数量
			
			if(isNormalImport==1)
			{
				inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", fdActualNumber);//有发票数量=0
				inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", 0);//无发票数量=实进数量
				inInfo.getBlock("result").setCell(i, "fdActualPrice", inInfo.getBlock("result").getCell(i, "fdPrice"));//实际单价=计划单价
				inInfo.getBlock("result").setCell(i, "fdActualSum", fdSum);//实际库存金额=库存金额
				inInfo.getBlock("result").setCell(i, "fdInvoiceSum", fdInvoiceSum);//实际库存金额=发票金额
			}
			else if(isNormalImport==2)
			{
				inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", 0);//有发票数量=实进数量
				inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", fdActualNumber);//无发票数量=0
				inInfo.getBlock("result").setCell(i, "fdActualPrice", (fdInvoiceSum/fdActualNumber));//实际单价=发票金额/实进数量
				inInfo.getBlock("result").setCell(i, "fdActualSum", 0);//发票金额=0
			}
			else
			{
				inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", 0);//有发票数量=0
				inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", 0);//无发票数量=0
				inInfo.getBlock("result").setCell(i, "fdActualPrice", inInfo.getBlock("result").getCell(i, "fdPrice"));//实际单价=计划单价
				inInfo.getBlock("result").setCell(i, "fdActualSum", fdSum);//实际库存金额=库存金额
				inInfo.getBlock("result").setCell(i, "fdInvoiceSum", 0);//发票金额=0
			}
			
			inInfo.getBlock("result").setCell(i, "fdPrice", basicInfo.getFdPrice());
			inInfo.getBlock("result").setCell(i, "fdSum", BigDecimal.valueOf(basicInfo.getFdPrice()*fdActualNumber));//库存金额为实收金额
			inInfo.getBlock("result").setCell(i, "fdLastImportDate", StaticTools.getDate());//最后进料日期为系统当前日期
		}
		super.insert(inInfo, "ZMCMMaterialBase.insertStorage");
	}
	
	/**
	 * 
	 * <p>Function: updateAll</p>
	 * <p>Description: </p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:30:34 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void updateAll(EiInfo inInfo, List<ZMCMMaterialBase> list, int isNormalImport){
		for(int i = 0; i < inInfo.getBlock("result").getRowCount(); i++){
			String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
			String actualNumber = inInfo.getBlock("result").getCellStr(i, "fdActualNumber");
			String invoiceSum = inInfo.getBlock("result").getCellStr(i, "fdInvoiceSum");
			String price = inInfo.getBlock("result").getCellStr(i, "fdPrice");

			double fdActualNumber = Double.parseDouble(actualNumber.equals("")? "0": actualNumber);
			double fdInvoiceSum = Double.parseDouble(invoiceSum.equals("")? "0": invoiceSum);
			double fdPrice = Double.parseDouble(price.equals("")? "0": price);
			
			Map inMap = new HashMap();
			inMap.put("fdKeyId", fdMaterialId);
			
			//List _list = dao.query("ZMCMMaterialBasicInfo.query", inMap);
			//ZMCMMaterialBasicInfo basicInfo = (ZMCMMaterialBasicInfo)_list.get(0);
			
			for(ZMCMMaterialBase mb : list){
				if(mb.getFdMaterialId().equals(fdMaterialId)){
					double fdActualSum = mb.getFdActualSum();
					double fdNum = 	mb.getFdNum();
					double fdHasinvoiceNum = 0.0;
					double fdNoinvoiceNum = 0.0;
					if(mb.getFdHasinvoiceNum()!=null)
						fdHasinvoiceNum = mb.getFdHasinvoiceNum();
					if(mb.getFdNoinvoiceNum()!=null)
						fdNoinvoiceNum = mb.getFdNoinvoiceNum();
					
					if(isNormalImport==1)
					{
						inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", fdActualNumber+fdHasinvoiceNum);//有发票数量
						inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", fdNoinvoiceNum);//无发票数量
						inInfo.getBlock("result").setCell(i, "fdActualSum", fdInvoiceSum+fdActualSum);//计算实际库存金额
						inInfo.getBlock("result").setCell(i, "fdActualPrice", (fdInvoiceSum+fdActualSum)/(fdActualNumber+fdNum));//计算实际单价
					}
					else if(isNormalImport==2)
					{
						inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", fdHasinvoiceNum);//有发票数量
						inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", fdActualNumber+fdNoinvoiceNum);//无发票数量
						inInfo.getBlock("result").setCell(i, "fdActualSum", 
								BigDecimal.valueOf(fdPrice*fdActualNumber+fdActualSum));//计算实际库存金额
						inInfo.getBlock("result").setCell(i, "fdActualPrice", 
								BigDecimal.valueOf((fdPrice*fdActualNumber+fdActualSum)/(fdActualNumber+fdNum)));//计算实际单价
					}
					else
					{
						inInfo.getBlock("result").setCell(i, "fdHasinvoiceNum", fdHasinvoiceNum);//有发票数量
						inInfo.getBlock("result").setCell(i, "fdNoinvoiceNum", fdNoinvoiceNum);//无发票数量
						inInfo.getBlock("result").setCell(i, "fdActualSum", 
								BigDecimal.valueOf(fdPrice*fdActualNumber+fdActualSum));//计算实际库存金额
						inInfo.getBlock("result").setCell(i, "fdActualPrice", 
								BigDecimal.valueOf((fdPrice*fdActualNumber+fdActualSum)/(fdActualNumber+fdNum)));//计算实际单价
					}
					
					//更新库存中已存在物资的数量、单价、计划单价等信息
					inInfo.getBlock("result").setCell(i, "fdPrice", mb.getFdPrice());
					inInfo.getBlock("result").setCell(i, "fdSum", BigDecimal.valueOf(mb.getFdPrice()*(fdActualNumber+fdNum)));
					inInfo.getBlock("result").setCell(i, "fdMaterialId", fdMaterialId);
					inInfo.getBlock("result").setCell(i, "fdNum", fdActualNumber+fdNum);
					inInfo.getBlock("result").setCell(i, "fdLastImportDate", StaticTools.getDate());
					
					break;
				}
			}
		}
		super.update(inInfo, "ZMCMMaterialBase.updateAfterStorage");
	}
	
	/**
	 * 
	 * <p>Function: part</p>
	 * <p>Description: </p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:31:17 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void part(EiInfo inInfo, List<ZMCMMaterialBase> list, int isNormalImport){
		List tempList = new ArrayList();
		
		for(int i = 0; i < inInfo.getBlock("result").getRowCount(); i++){
			String fdMaterialId = inInfo.getBlock("result").getCellStr(i, "fdMaterialId");
			for(ZMCMMaterialBase mb : list){
				if(mb.getFdMaterialId().equals(fdMaterialId)){
					tempList.add(inInfo.getBlock("result").getRow(i));
					break;
				}
			}
		}
		
		//构造一个用于更新的EiInfo
		EiInfo updateInfo = new EiInfo();
		updateInfo.addBlock("result").addBlockMeta(new ZMCMMaterialBase().eiMetadata);
		updateInfo.getBlock("result").addRows(tempList);
		
		List insertList = new ArrayList();
		insertList.addAll(inInfo.getBlock("result").getRows());
		insertList.removeAll(tempList);
		
		//构造一个用于新增的EiInfo
		EiInfo insertInfo = new EiInfo();
		insertInfo.addBlock("result").addBlockMeta(new ZMCMMaterialBase().eiMetadata);
		insertInfo.getBlock("result").addRows(insertList);
		
		this.insertAll(insertInfo, isNormalImport);
		this.updateAll(updateInfo, list, isNormalImport);
	}
	
	/**
	 * 
	 * <p>Function: validateCode</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:31:31 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo validateCode(EiInfo inInfo)
	{
		Map params = new HashMap();
		params.put("fdNoteCode", inInfo.get("fdNoteCode"));
		
		List result = dao.query("ZMCMImportMaterial.validate", params);
		if(result != null && result.size() > 0)
		{
			inInfo.setStatus(-1);
			StringBuffer msg = new StringBuffer("单据编号重复！");
			inInfo.setMsg(msg.toString());
			
			return inInfo;
		}
		
		String date1 = inInfo.getString("fdNoteDate");		
		if(date1 == null || "".equals(date1))//如果没有得到日期，默认为当前日期
		{
			date1 = StaticTools.getDate();
		}
		int result_int = MaterialBase.isInAccountDate(date1);
		if(result_int == -2)
		{
			inInfo.setStatus(-1);
			//StringBuffer msg = new StringBuffer("当前日期已经超出" + MaterialBase.getAccountDate(StaticTools.getDate())[2] + "月的记账范围，请在结转库存后，再办理入库！");
			StringBuffer msg = new StringBuffer("上个月没有做库存结转，请在结转库存后，再办理入库！");
			inInfo.setMsg(msg.toString());
			return inInfo;
		}
		if(result_int == 0)
		{
			inInfo.setStatus(-1);
			StringBuffer msg = new StringBuffer("该开单日期所在" + MaterialBase.getAccountDate(date1)[2] + "月的库存已经结转，无法办理入库！");
			inInfo.setMsg(msg.toString());
			return inInfo;
		}
		return inInfo;
	}
	
	/**
	 * 
	 * <p>Function: queryNoteCode</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:31:43 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo queryNoteCode(EiInfo inInfo)
	{
		List<Map> _list = new ArrayList<Map>();
		HashMap	params = new HashMap<String, String>();
		String startStr = "RK" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		String defaultStr = startStr + "001";//定义格式
		_list = dao.query("ZMCMImportMaterial.querySerialNum", params);
		if(_list!=null && _list.size() > 0) {
			String str = _list.get(0).get("fdNoteCode").toString();
			defaultStr = convertStr(startStr, str);
		}
		
		inInfo.set("fdNoteCode", defaultStr);
		
		return inInfo;
	}
	
	/**
	 * 
	 * <p>Function: convertStr</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:31:56 严洪浩
	 * </p>
	 *
	 */
	private String convertStr(String startStr, String str)
	{
		String str1 = str.substring(16,19);//第二部分的流水号
		int nub = Integer.parseInt(str1); 
		str1 = Integer.toString(nub+1);
		if(str1.length() == 1){
			return startStr+"00"+str1;
		}else if (str1.length() == 2)
		{
			return startStr+"0"+str1;
		}else
		{
			return startStr+str1;
		}
	}
}
